/**
 * 文件下载
 * @param {*} response -返回体
 */
export const exportFile = function(response) {
  console.log('download---', response)
  const res = response.data || {}
  const type = response.headers['content-type']
  const fileName = decodeURI((response.headers['content-disposition'] || '').split('filename=')[1] || '')
  const blob = new Blob([res], { type })
  const url = URL.createObjectURL(blob)

  // 获取heads中的filename文件名
  const downloadElement = document.createElement('a')
  // 创建下载的链接
  document.body.appendChild(downloadElement)
  downloadElement.download = decodeURI(fileName || '')
  downloadElement.href = url
  // 点击下载
  downloadElement.click()
  // 下载完成移除元素
  document.body.removeChild(downloadElement)
}

/**
 * 本地缓存方法调用优化
 * @param {*} type
 * @returns
 */
export const useStorage = function(type = 'sessionStorage') {
  const storageMap = new Map([['sessionStorage', sessionStorage], ['localStorage', localStorage]])
  let storage = storageMap.get(type)
  if (!storage) throw new Error('Please provide the matching key for storage')
  // 访问本地storage
  const getItem = function(key, toJSON, _type) {
    if (!key) throw new Error('Please provide the key for storage')
    if (_type) {
      storage = storageMap.get(_type)
    }
    const value = storage.getItem(key)
    if (toJSON && !value) {
      return value
    }
    return toJSON ? JSON.parse(value) : value
  }
  // 设置本地storage
  const setItem = function(key, value, toJSON, _type) {
    if (!key) throw new Error('Please provide the key for storage')
    if (value === null || value === undefined) {
      throw new Error("the value can't be null or undefined")
    }
    if (_type) {
      storage = storageMap.get(_type)
    }
    storage.setItem(key, toJSON ? JSON.stringify(value) : value)
  }
  return {
    getItem,
    setItem
  }
}

/**
 * 引用类型深拷贝
 * @param {*} obj
 * @returns
 */
export const deepClone = function(obj) {
  const isObject = (val) => val !== null && typeof val === 'object'
  // 基本数据类型直接返回
  if (!isObject(obj)) return obj
  const result = Array.isArray(obj) ? [] : {}
  for (const key in obj) {
    const val = obj[key]
    if (isObject) {
      result[key] = deepClone(val)
    } else {
      result[key] = val
    }
  }
  return result
}

// 从url 地址中提取query 参数
export const extractQuery = (url) => {
  const idx = url.lastIndexOf('?')
  if (idx === -1) return null
  const queryStr = url.substring(idx + 1)
  if (!queryStr.length) return null
  const queryArr = queryStr.split('&')
  return queryArr.reduce((accu, curr) => {
    const [key, value] = curr.split('=')
    if (key) { accu[key] = value || '' }
    return accu
  }, {})
}

// 移除树结构中空节点
export function delEmptyChildren(treeData = [], prop = 'children') {
  const iterationFunc = function(tree) {
    return tree.map((item) => {
      if (Array.isArray(item[prop]) && item[prop].length > 0) {
        item[prop] = iterationFunc(item[prop])
      } else {
        delete item[prop]
      }
      return item
    })
  }
  return iterationFunc(treeData)
}
